#!/usr/bin/env python

import hmac
import base64
from hashlib import sha1
import time
from paho.mqtt.client import MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, MQTT_LOG_ERR, MQTT_LOG_DEBUG, unicode

from paho.mqtt import client as mqtt

# accessKey get from aliyun account console
accessKey = 'LTAIBG4ljI6DSaLf'
# secretKey get from aliyun account console
secretKey = '9SNiwEMjhgxD991LHswvlKpjAtnyAP'
# MQTT GroupID,get from mq console
groupId = 'GID_POS_TEST'
client_id = groupId + '@@@' + 'PYTHONTEST00002'
# Topic
topic = 'FC_POS_MQTT_TEST'
# MQTT endPoint get from mq console
brokerUrl = 'post-cn-mp90idz2w09.mqtt.aliyuncs.com'


def on_log(client, userdata, level, buf):
    if level == MQTT_LOG_INFO:
        head = 'INFO'
    elif level == MQTT_LOG_NOTICE:
        head = 'NOTICE'
    elif level == MQTT_LOG_WARNING:
        head = 'WARN'
    elif level == MQTT_LOG_ERR:
        head = 'ERR'
    elif level == MQTT_LOG_DEBUG:
        head = 'DEBUG'
    else:
        head = level
    print('%s: %s' % (head, buf))


def on_connect(client, userdata, flags, rc):
    print('Connected with result code ' + str(rc))


def on_disconnect(client, userdata, rc):
    if rc != 0:
        print('Unexpected disconnection %s' % rc)


client = mqtt.Client(client_id,clean_session=False, protocol=mqtt.MQTTv311)
client.on_log = on_log
client.on_connect = on_connect
client.on_disconnect = on_disconnect
password = base64.b64encode(hmac.new(secretKey.encode(), groupId.encode(), sha1).digest()).decode()
client.username_pw_set(accessKey, password)
client.connect(brokerUrl, 1883, 60)
# 发送消息
rc = client.publish(topic, bytes("hello aliyun-kafka32323测试2", encoding='utf-8'), qos=1)
print(rc)
time.sleep(0.1)
